const express = require("express")
let router = express.Router()

const query = require("../tools/db")
const { api_url } = require("../config/config")




// 需要自主完善------------------
router.get("/searchlist", async (req, res, next) => {

    // 希望用户传递一个搜索的参数，一个页码参数 
    // 希望前端传递 一页展示多少数据
    let { searchvalue, page = 1, size = 6 } = req.query
    if (!searchvalue) {
        next("请输入搜索内容")
        return
    }

    // index  下标，从哪个数据开始拿取
    // size 拿取几条，一页展示多少数据
    // page 当前页码
    let index = size * (page - 1)

    let sql = `select 
                    id,
                    cid,
                    title,
                    price,
                    concat("${api_url}","/uploads/","index/",image_src) as image_src,
                    area_name,
                    subject_name 
             from e_course 
             where  title like "%${searchvalue}%" 
             or area_name like "%${searchvalue}%" 
             or type_name like "%${searchvalue}%" 
             or grade_name like "%${searchvalue}%" 
             or subject_name like "%${searchvalue}%" 
             or category_name like "%${searchvalue}%" 
             limit ${index},${size}
            `
    let [err, results] = await query(sql)
    if (err) {
        next("搜索失败")
        return
    }



    // 总数量
    let sql1 = `select 
                    *
                from e_course 
                where  title like "%${searchvalue}%" 
                or area_name like "%${searchvalue}%" 
                or type_name like "%${searchvalue}%" 
                or grade_name like "%${searchvalue}%" 
                or subject_name like "%${searchvalue}%" 
                or category_name like "%${searchvalue}%"`


    let [err1, results1] = await query(sql1)
    if (err1) {
        next("搜索失败")
        return
    }
    // res.send(results1)
    // return
    let rows=results1.length
    let pages=Math.ceil(rows/size)


    res.send({
        status: 200,
        msg: "搜索成功",
        results: {
            data: results,
            page: Number(page),
            rows,
            pages
        }
    })
})



module.exports = router